package com.yingjia.yingjiauniversity.utils;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.DrawableRes;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

import static com.bumptech.glide.load.DecodeFormat.PREFER_ARGB_8888;

/**
 * @author tangpeng.yang.o(tangpeng.yang.o @ nio.com)
 * @date 2017-10-13 19:59
 * Description:
 * FIXME
 */

public class GlideUtil {

    public static void setUri(Context context, final ImageView view, String uri) {

        if (StringUtil.isEmpty(uri)) {
            return;
        }
        if (!isContextAvailable(context)) {
            return;
        }
        Glide.with(context).load(uri).asBitmap().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                view.setImageBitmap(bitmap);
            }
        });
    }

    public static void setUri(Context context, ImageView view, @DrawableRes int defaultImg, String uri) {
        if (StringUtil.isEmpty(uri)) {
            view.setImageResource(defaultImg);
            return;
        }
        if (!isContextAvailable(context)) {
            return;
        }
        Glide.with(context)
                .load(uri)
                .asBitmap()
                .placeholder(defaultImg)
                .dontAnimate()
                .error(defaultImg)
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .into(view);
    }

    public static void setUri(Context context, final ImageView view, @DrawableRes int defaultImg, @DrawableRes int errorImg, String uri) {

        if (StringUtil.isEmpty(uri)) {
            return;
        }
        if (!isContextAvailable(context)) {
            return;
        }
        Glide.with(context)
                .load(uri)
                .asBitmap()
                .placeholder(defaultImg).error(errorImg).diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                        view.setImageBitmap(bitmap);
                    }
                });
    }

    /**
     * 可设置图片角度的加载方式
     *
     * @param degree 图片需要旋转的角度
     */
    public static void setUri(Context context, ImageView view, @DrawableRes int defaultImg, @DrawableRes int errorImg, String uri,
                              int degree) {

        if (StringUtil.isEmpty(uri)) {
            return;
        }
        if (!isContextAvailable(context)) {
            return;
        }
        Glide.with(context)
                .load(uri)
                .asBitmap()
                .placeholder(defaultImg)
                .error(errorImg)
                .into(view);
    }

    /**
     * 可设置图片圆角的加载方式
     *
     * @param radius 图片圆角度数
     */
    public static void setUriWithRound(Context context, ImageView view, @DrawableRes int defaultImg, @DrawableRes int errorImg, String uri,
                                       int radius) {

        if (StringUtil.isEmpty(uri)) {
            return;
        }
        if (!isContextAvailable(context)) {
            return;
        }
        Glide.with(context)
                .load(uri)
                .asBitmap()
                .transform(new RoundTransformation(context, radius))
                .placeholder(defaultImg)
                .error(errorImg)
                .into(view);
    }

    public static void setUri(Context context, ImageView view, @DrawableRes int defaultImg, String uri, int width, int height) {
        if (StringUtil.isEmpty(uri)) {
            return;
        }

        if (!isContextAvailable(context)) {
            return;
        }
        Glide.with(context)
                .load(uri)
                .asBitmap()
                .placeholder(defaultImg)
                .dontAnimate()
                .error(defaultImg)
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .override(width, height)
                .priority(Priority.HIGH)
                .format(PREFER_ARGB_8888)
                .centerCrop()
                .into(view);
    }

    /**
     * 图片圆角转换器
     * <p>
     * 只做左上，右上的圆角处理
     */
    public static class RoundTransformation extends BitmapTransformation {

        private float radius = 0f;

        public RoundTransformation(Context context) {
            this(context, 4);
        }

        public RoundTransformation(Context context, int dp) {
            super(context);
            this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
        }

        @Override
        protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
            return roundCrop(pool, toTransform);
        }

        private Bitmap roundCrop(BitmapPool pool, Bitmap source) {
            if (source == null) return null;

            Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
            if (result == null) {
                result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
            }

            Canvas canvas = new Canvas(result);
            Paint paint = new Paint();
            paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
            paint.setAntiAlias(true);
            RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
            canvas.drawRoundRect(rectF, radius, radius, paint);

            //只做左上，右上的圆角处理
            canvas.drawRect(0, canvas.getHeight() - radius, radius, canvas.getHeight(), paint);
            canvas.drawRect(canvas.getWidth() - radius, canvas.getHeight() - radius, canvas.getWidth(), canvas.getHeight(), paint);
            return result;
        }

        @Override
        public String getId() {
            return getClass().getName() + Math.round(radius);
        }
    }

    /**
     * 图片角度变换器
     */
    public static class RotateTransformation extends BitmapTransformation {

        private float rotateRotationAngle = 0f;

        public RotateTransformation(Context context, float rotateRotationAngle) {
            super(context);

            this.rotateRotationAngle = rotateRotationAngle;
        }

        @Override
        protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
            Matrix matrix = new Matrix();

            matrix.postRotate(rotateRotationAngle);

            return Bitmap.createBitmap(toTransform, 0, 0, toTransform.getWidth(), toTransform.getHeight(), matrix, true);
        }

        @Override
        public String getId() {
            return "rotate" + rotateRotationAngle;
        }
    }

//  public static void setRealyUri(Context context, final ImageView view, @DrawableRes int defaultImg, String uri, final int width,
//                                 final int height) {
//    if (StringUtil.isEmpty(uri)) {
//      return;
//    }
//    if (!isContextAvailable(context)) {
//      return;
//    }
//    Glide.with(context).load(uri).asBitmap().into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
//      @Override public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
//        view.setImageBitmap(ImageUtil.zoomBitmap(resource, width, height));
//      }
//    });
//  }

    public static boolean isContextAvailable(Context context) {
        if (context instanceof Activity) {
            if (((Activity) context).isFinishing() || ((Activity) context).isDestroyed()) {
                return false;
            }
        } else if (context == null) {
            return false;
        }
        return true;
    }
}
